function getUrlParms(name) {
  var reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)")
  var r = window.location.search.substr(1).match(reg)
  if (r != null) return decodeURI(r[2])
  return null
}
let id = getUrlParms("id")

if (!id || !localStorage.getItem(id)) {
  window.location.href = "/view/questionnaire-list/questionnaire-list.html"
}

let dialog = document.getElementById("my-dialog")

let questionnaire = JSON.parse(localStorage.getItem(id))

document.getElementById("title").innerHTML = questionnaire.title

let questionList = questionnaire.questionList

let questionContainer = document.querySelector(".question-container")

questionList.forEach((question, index) => {
  let questionItem = document.createElement("question-item")
  questionItem.setAttribute(
    "question",
    JSON.stringify({ index: index + 1, ...question })
  )
  questionContainer.appendChild(questionItem)
})

document
  .getElementById("question-form")
  .addEventListener("submit", function (e) {
    e.preventDefault()
    let form = new FormData(this)
    try {
      questionList.forEach((question, index) => {
        let answerList = form.getAll(`question-${index + 1}`)
        if (
          (answerList.length === 0 || answerList.includes("")) &&
          !question.optional
        ) {
          throw new Error("请填写所有必填项")
        }
      })
    } catch (error) {
      dialog.setAttribute("visible", 1)
      return
    }

    questionList.forEach((question, index) => {
      let answerList = form.getAll(`question-${index + 1}`)
      answerList.forEach((answer) => {
        let question = questionList[index]
        question.datas.forEach((option, index) => {
          if (option.name === answer || question.type == 3) {
            option.value++
          }
        })
      })
    })

    questionnaire.questionList = questionList

    localStorage.setItem(id, JSON.stringify(questionnaire))

    dialog.innerHTML = "填写成功， 返回问卷列表页"
    dialog.setAttribute("visible", 1)

    setTimeout(() => {
      location.href = "/view/questionnaire-list/questionnaire-list.html"
    }, 1000)
  })
